import React, { useState, useRef, useEffect } from 'react';
import { Message, ChatState, Conversation, KnowledgeFile } from './types';
import { ChatMessage } from './components/ChatMessage';
import { ChatInput } from './components/ChatInput';
import { ConversationList } from './components/ConversationList';
import { KnowledgeBase } from './components/KnowledgeBase';
import { Login } from './components/Login';
import { Book, ChevronLeft, ChevronRight, Bot } from 'lucide-react';
import { userApi, knowledgeApi, chatApi, searchApi } from './services/api';
import { TypingIndicator } from './components/TypingIndicator';
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { Home } from './pages/Home';
import { Register } from './pages/Register';

// 主应用容器
function App() {
  return (
    <BrowserRouter>
      <AppContent />
    </BrowserRouter>
  );
}

// 实际内容组件
function AppContent() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [showRegister, setShowRegister] = useState(false);
  const [state, setState] = useState<ChatState>({
    conversations: [],
    activeConversationId: null,
    isTyping: false,
    searchQuery: ''
  });
  
  const [knowledgeFiles, setKnowledgeFiles] = useState<KnowledgeFile[]>([]);
  const [showKnowledgeBase, setShowKnowledgeBase] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [state.conversations]);

  // 监听活跃会话变化，自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [state.activeConversationId]);

  // 监听消息变化，自动滚动到底部
  useEffect(() => {
    const activeConversation = state.conversations.find(
      conv => conv.id === state.activeConversationId
    );
    
    if (activeConversation) {
      scrollToBottom();
    }
  }, [state.conversations, state.activeConversationId]);

  // Load conversations from localStorage on mount
  useEffect(() => {
    const savedConversations = localStorage.getItem('conversations');
    if (savedConversations) {
      const parsed = JSON.parse(savedConversations);
      setState(prev => ({
        ...prev,
        conversations: parsed.map((conv: any) => ({
          ...conv,
          timestamp: new Date(conv.timestamp)
        }))
      }));
    }

    // Load knowledge files
    const savedFiles = localStorage.getItem('knowledgeFiles');
    if (savedFiles) {
      setKnowledgeFiles(JSON.parse(savedFiles).map((file: any) => ({
        ...file,
        uploadedAt: new Date(file.uploadedAt)
      })));
    }
  }, []);

  // Save conversations to localStorage when updated
  useEffect(() => {
    localStorage.setItem('conversations', JSON.stringify(state.conversations));
  }, [state.conversations]);

  // Save knowledge files to localStorage when updated
  useEffect(() => {
    localStorage.setItem('knowledgeFiles', JSON.stringify(knowledgeFiles));
  }, [knowledgeFiles]);

  // 加载会话列表函数
  const loadSessionList = async () => {
    try {
      console.log('开始加载会话列表...');
      const response = await chatApi.getSessionList();
      
      if (response.code === 1) {
        console.log('成功获取会话列表:', response.data);
        
        // 转换会话数据格式，使用 createdAt 作为时间戳
        const conversations = response.data.map((session: any) => ({
          id: session.id.toString(),
          title: session.title || '新对话',
          // 移除 lastMessage 属性
          timestamp: session.createdAt ? new Date(session.createdAt) : new Date(),
          messages: [] // 初始为空数组，选择会话时再加载详情
        }));
        
        setState(prev => ({
          ...prev,
          conversations,
          // 不设置活跃会话ID，这样用户登录后会看到欢迎界面
          activeConversationId: null
        }));
      } else {
        console.warn('获取会话列表失败:', response.msg);
      }
    } catch (error) {
      console.error('加载会话列表失败:', error);
    }
  };

  // 检查用户是否已登录
  useEffect(() => {
    const token = localStorage.getItem('webToken');
    if (token) {
      setIsAuthenticated(true);
      // 不在这里加载会话列表，而是在认证状态变化时加载
    }
  }, []);

  // 监听认证状态变化
  useEffect(() => {
    console.log('认证状态变化:', isAuthenticated);
    
    // 当用户认证状态变为 true 时，加载会话列表和知识库文档列表
    if (isAuthenticated) {
      loadSessionList();
      loadKnowledgeFiles();
    }
  }, [isAuthenticated]);

  // 监听知识库模态框打开状态
  useEffect(() => {
    if (showKnowledgeBase && isAuthenticated) {
      loadKnowledgeFiles();
    }
  }, [showKnowledgeBase, isAuthenticated]);

  // 处理登录
  const handleLogin = async (username: string, password: string) => {
    try {
      const response = await userApi.login(username, password);
      console.log('登录响应:', response);
      
      if (response.code === 1) {
        console.log('登录成功:', response.data);
        
        // 添加安全检查
        if (!response.data) {
          console.warn('登录成功但未返回用户数据，使用默认值');
          localStorage.setItem('webToken', response.token || 'default-token');
          localStorage.setItem('userId', '1');
          localStorage.setItem('username', username);
        } else {
          localStorage.setItem('webToken', response.data.token || response.token || 'default-token');
          
          let userId = '1';
          if (response.data.userId !== undefined && response.data.userId !== null) {
            userId = String(response.data.userId);
          } else if (response.data.id !== undefined && response.data.id !== null) {
            userId = String(response.data.id);
          } else if (response.userId !== undefined && response.userId !== null) {
            userId = String(response.userId);
          }
          
          localStorage.setItem('userId', userId);
          localStorage.setItem('username', username);
        }
        
        // 更新认证状态
        setIsAuthenticated(true);
        
        // 使用 window.location.href 强制刷新页面并重定向到根路径
        window.location.href = '/';
      } else {
        console.warn('登录失败:', response.msg);
        throw new Error(response.msg || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  };

  // 处理注册
  const handleRegister = async (username: string, email: string, password: string) => {
    try {
      const response = await userApi.register(username, email, password);
      if (response.code === 200) {
        // 注册成功后自动切换到登录页
        setShowRegister(false);
      } else {
        throw new Error(response.msg || '注册失败');
      }
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  };

  // 处理注销
  const handleLogout = () => {
    // 调用 API 注销
    userApi.logout();
    
    // 清除本地存储
    localStorage.removeItem('webToken');
    localStorage.removeItem('userId');
    localStorage.removeItem('username');
    
    // 重置状态
    setIsAuthenticated(false);
    setState({
      conversations: [],
      activeConversationId: null,
      isTyping: false,
      searchQuery: ''
    });
    
    console.log('用户已注销');
  };

  // 在 App 组件中添加全局错误处理
  useEffect(() => {
    // 处理认证错误
    const handleAuthError = (event: CustomEvent) => {
      console.log('收到认证错误事件:', event.detail);
      
      // 显示错误消息，但不自动跳转
      // 可以使用 toast 或其他通知组件
      alert(event.detail.message || '认证已过期，请重新登录');
      
      // 可选：如果用户当前已认证，将其设置为未认证
      if (isAuthenticated) {
        setIsAuthenticated(false);
      }
    };
    
    // 添加事件监听器
    window.addEventListener('authError', handleAuthError as EventListener);
    
    // 清理函数
    return () => {
      window.removeEventListener('authError', handleAuthError as EventListener);
    };
  }, [isAuthenticated]);

  // 如果用户未登录，显示登录页面
  if (!isAuthenticated) {
    return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login onLogin={handleLogin} onRegisterClick={() => navigate('/register')} />} />
        <Route path="/register" element={<Register />} />
        {/* 将其他路由重定向到首页 */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    );
  }

  const simulateKnowledgeSearch = async (query: string): Promise<{ content: string; source?: { fileName: string; fileId: string } }> => {
    // Simulate searching through knowledge base
    const relevantFile = knowledgeFiles.find(file => 
      file.content?.toLowerCase().includes(query.toLowerCase())
    );

    if (relevantFile) {
      return {
        content: `Based on the knowledge base (${relevantFile.name}): This is a simulated response from the knowledge base.`,
        source: {
          fileName: relevantFile.name,
          fileId: relevantFile.id
        }
      };
    }

    return {
      content: `I couldn't find relevant information in the knowledge base. Here's a general response: "${query}"\nThis is a simulated AI response.`
    };
  };

  const simulateAIResponse = async (userMessage: string) => {
    setState(prev => ({ ...prev, isTyping: true }));
    
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const response = await simulateKnowledgeSearch(userMessage);
    
    const aiMessage: Message = {
      id: Date.now().toString(),
      content: response.content,
      sender: 'ai',
      timestamp: new Date(),
      status: 'sent',
      source: response.source
    };
    
    setState(prev => {
      const updatedConversations = prev.conversations.map(conv => {
        if (conv.id === prev.activeConversationId) {
          return {
            ...conv,
            messages: [...conv.messages, aiMessage],
            timestamp: new Date()
          };
        }
        return conv;
      });

      return {
        ...prev,
        conversations: updatedConversations,
        isTyping: false
      };
    });
  };

  // 刷新会话列表
  const refreshSessionList = async (updateUI = true) => {
    try {
      const response = await chatApi.getSessionList();
      
      if (response.code === 1) {
        console.log('刷新会话列表成功:', response.data);
        
        if (!updateUI) {
          console.log('静默刷新，不更新 UI');
          return;
        }
        
        // 转换会话数据格式
        const conversations = response.data.map((session: any) => ({
          id: session.id.toString(),
          title: session.title || '新对话',
          timestamp: session.createdAt ? new Date(session.createdAt) : new Date(),
          messages: [] // 初始为空数组，选择会话时再加载详情
        }));
        
        // 保留当前活跃会话ID和消息
        const activeId = state.activeConversationId;
        const activeConversation = state.conversations.find(c => c.id === activeId);
        const activeMessages = activeConversation ? activeConversation.messages : [];
        
        setState(prev => {
          // 合并新的会话列表，但保留当前活跃会话的消息
          const mergedConversations = conversations.map(newConv => {
            if (newConv.id === activeId) {
              return {
                ...newConv,
                messages: activeMessages
              };
            }
            
            // 查找旧会话中是否有对应的消息
            const oldConv = prev.conversations.find(c => c.id === newConv.id);
            if (oldConv && oldConv.messages.length > 0) {
              return {
                ...newConv,
                messages: oldConv.messages
              };
            }
            
            return newConv;
          });
          
          return {
            ...prev,
            conversations: mergedConversations,
            activeConversationId: activeId
          };
        });
      } else {
        console.warn('刷新会话列表失败:', response.msg);
      }
    } catch (error) {
      console.error('刷新会话列表失败:', error);
    }
  };

  // 添加防抖函数
  const debounce = <T extends (...args: any[]) => any>(func: T, wait: number) => {
    let timeout: ReturnType<typeof setTimeout>;
    return function executedFunction(...args: Parameters<T>) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  };

  // 使用防抖处理刷新会话列表
  const debouncedRefreshSessionList = debounce(refreshSessionList, 500);

  // 处理发送消息
  const handleSendMessage = async (content: string) => {
    if (!content.trim()) return;

    console.log('准备发送消息:', content);
    
    // 创建用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      content,
      sender: 'user',
      timestamp: new Date(),
      status: 'sending'
    };

    // 获取当前活跃会话
    const currentConversation = state.activeConversationId 
      ? state.conversations.find(c => c.id === state.activeConversationId)
      : null;

    let sessionId: string | null = state.activeConversationId;

    // 如果没有活跃会话，创建一个新会话
    if (!currentConversation) {
      try {
        // 调用创建会话API
        const response = await chatApi.createSession();
        
        if (response.code === 1) {
          console.log('新会话创建成功:', response.data);
          sessionId = response.data.toString();
          
          setState(prev => ({
            ...prev,
            activeConversationId: sessionId,
            conversations: [
              {
                id: sessionId!,
                title: content.slice(0, 30),
                timestamp: new Date(),
                messages: [userMessage]
              },
              ...prev.conversations
            ],
            isTyping: true
          }));
        } else {
          console.error('创建会话失败:', response.msg);
          // 使用临时会话ID继续
          sessionId = `temp-${Date.now()}`;
          
          setState(prev => ({
            ...prev,
            activeConversationId: sessionId,
            conversations: [
              {
                id: sessionId!,
                title: content.slice(0, 30),
                timestamp: new Date(),
                messages: [userMessage]
              },
              ...prev.conversations
            ],
            isTyping: true
          }));
        }
      } catch (error) {
        console.error('创建会话错误:', error);
        // 使用临时会话ID继续
        sessionId = `temp-${Date.now()}`;
        
        setState(prev => ({
          ...prev,
          activeConversationId: sessionId,
          conversations: [
            {
              id: sessionId!,
              title: content.slice(0, 30),
              timestamp: new Date(),
              messages: [userMessage]
            },
            ...prev.conversations
          ],
          isTyping: true
        }));
      }
    } else {
      console.log('添加消息到现有会话:', state.activeConversationId);
      
      // 添加用户消息到现有会话
      setState(prev => ({
        ...prev,
        conversations: prev.conversations.map(conv => {
          if (conv.id === prev.activeConversationId) {
            return {
              ...conv,
              messages: [...conv.messages, userMessage],
              timestamp: new Date()
            };
          }
          return conv;
        }),
        isTyping: true
      }));
    }

    try {
      // 创建AI消息占位符，但这次不立即添加到会话中
      const aiMessageId = `ai-${Date.now()}`;
      let aiMessageAdded = false;
      
      // 调用流式聊天API
      const closeConnection = await chatApi.streamChat(content, sessionId!, {
        onReady: () => {
          console.log('准备接收AI回复');
        },
        
        onTitle: (title) => {
          console.log('收到会话标题:', title);
          // 更新会话标题
          setState(prev => ({
            ...prev,
            conversations: prev.conversations.map(conv => {
              if (conv.id === sessionId) {
                return { ...conv, title };
              }
              return conv;
            })
          }));
        },
        
        onContent: (contentChunk) => {
          console.log('收到内容块:', contentChunk);
          
          setState(prev => {
            // 查找当前会话
            const currentConv = prev.conversations.find(c => c.id === prev.activeConversationId);
            if (!currentConv) return prev;
            
            // 查找是否已有AI回复消息
            const existingAiMsg = currentConv.messages.find(m => m.sender === 'ai' && m.id.startsWith('ai-') && m.status === 'sending');
            
            if (existingAiMsg) {
              // 如果已有AI消息，更新内容
              return {
                ...prev,
                conversations: prev.conversations.map(conv => {
                  if (conv.id === prev.activeConversationId) {
                    return {
                      ...conv,
                      messages: conv.messages.map(msg => 
                        msg.id === existingAiMsg.id 
                          ? { ...msg, content: msg.content + contentChunk } 
                          : msg
                      )
                    };
                  }
                  return conv;
                })
              };
            } else {
              // 如果没有AI消息，创建新消息
              aiMessageAdded = true;
              const newAiMessage: Message = {
                id: aiMessageId,
                content: contentChunk,
                sender: 'ai',
                timestamp: new Date(),
                status: 'sending'
              };
              
              return {
                ...prev,
                conversations: prev.conversations.map(conv => {
                  if (conv.id === prev.activeConversationId) {
                    return {
                      ...conv,
                      messages: [
                        ...conv.messages.map(msg => 
                          msg.id === userMessage.id ? { ...msg, status: 'sent' } : msg
                        ),
                        newAiMessage
                      ]
                    };
                  }
                  return conv;
                }),
                // 不关闭 isTyping 状态，保持 AI 回复中的状态
                isTyping: true
              };
            }
          });
          
          // 自动滚动到底部
          scrollToBottom();
        },
        
        onFinish: () => {
          console.log('AI回复完成');
          // 更新所有消息状态
          setState(prev => ({
            ...prev,
            conversations: prev.conversations.map(conv => {
              if (conv.id === prev.activeConversationId) {
                // 查找AI消息
                const aiMsg = conv.messages.find(m => m.sender === 'ai' && m.status === 'sending');
                
                if (aiMsg) {
                  // 更新AI消息状态
                  const updatedMessages = conv.messages.map(msg => 
                    msg.id === aiMsg.id ? { ...msg, status: 'sent' } : msg
                  );
                  
                  return {
                    ...conv,
                    messages: updatedMessages,
                    timestamp: new Date()
                  };
                }
                return conv;
              }
              return conv;
            }),
            isTyping: false
          }));
          
          // 延迟刷新会话列表
          setTimeout(() => {
            refreshSessionList(false);
          }, 1000);
        },
        
        onError: (error) => {
          console.error('流式对话错误:', error);
          // 错误处理...
        }
      });
      
      // 注意: 成功调用API后立即返回清理函数，而不是存储以供后续使用
      return () => closeConnection();
    } catch (error) {
      // 错误处理...
    }
  };

  // 加载知识库文档列表
  const loadKnowledgeFiles = async () => {
    try {
      console.log('开始加载知识库文档列表...');
      const response = await knowledgeApi.getFiles();
      
      if (response.code === 1) {
        console.log('成功获取知识库文档列表:', response.data);
        
        // 检查响应数据是否为数组
        if (!Array.isArray(response.data)) {
          console.warn('知识库文档列表数据不是数组:', response.data);
          setKnowledgeFiles([]);
          return;
        }
        
        // 转换文档数据格式，添加安全检查
        const files = response.data.map((file: any) => {
          // 打印每个文件对象，帮助调试
          console.log('处理文件对象:', file);
          
          // 确保 file 和必要的属性存在
          if (!file) {
            console.warn('文件对象为空');
            return null;
          }
          
          // 根据 documentDetailVO 的结构映射属性
          return {
            id: file.id ? String(file.id) : `temp-${Date.now()}`,
            name: file.title || '未命名文档',
            size: 0, // 接口中没有提供文件大小
            type: file.url ? file.url.split('.').pop() || 'unknown' : 'unknown',
            uploadedAt: file.createdAt ? new Date(file.createdAt) : new Date(),
            embeddingStatus: file.isEmbedding === 1 ? 'completed' : 'pending',
            url: file.url || '',
            lastEmbeddedAt: undefined // 接口中没有提供最后嵌入时间
          };
        }).filter(Boolean); // 过滤掉 null 值
        
        console.log('转换后的文件列表:', files);
        setKnowledgeFiles(files);
      } else {
        console.warn('获取知识库文档列表失败:', response.msg);
        setKnowledgeFiles([]);
      }
    } catch (error) {
      console.error('加载知识库文档列表失败:', error);
      console.error('错误详情:', error instanceof Error ? error.message : String(error));
      console.error('错误堆栈:', error instanceof Error ? error.stack : '无堆栈信息');
      setKnowledgeFiles([]);
    }
  };

  // 处理文件上传
  const handleFileUpload = async (file: File) => {
    try {
      console.log('开始上传文件:', file.name);
      const response = await knowledgeApi.uploadFile(file);
      
      if (response.code === 1 || response.code === 200) {
        console.log('文件上传成功:', response.data);
        
        // 上传成功后刷新知识库文档列表
        loadKnowledgeFiles();
        
        return response.data;
      } else {
        console.warn('文件上传失败:', response.msg);
        throw new Error(response.msg || '文件上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      throw error;
    }
  };

  // 处理文件删除
  const handleFileDelete = async (fileId: string) => {
    try {
      const response = await knowledgeApi.deleteFile(fileId);
      
      if (response.code === 1) {
        console.log('文件删除成功:', response.data);
        
        // 删除成功后刷新知识库文档列表
        loadKnowledgeFiles();
        
        return response.data;
      } else {
        console.warn('文件删除失败:', response.msg);
        throw new Error(response.msg || '文件删除失败');
      }
    } catch (error) {
      console.error('文件删除失败:', error);
      throw error;
    }
  };

  const handleFilePreview = async (fileId: string) => {
    try {
      const response = await knowledgeApi.previewFile(fileId);
      
      if (response.code === 200) {
        // 显示文件预览内容
        // 这里可以使用模态框或其他方式展示预览内容
        console.log('文件预览内容:', response.data.content);
        
        // 更新文件内容
        setKnowledgeFiles(prev => 
          prev.map(file => 
            file.id === fileId 
              ? { ...file, content: response.data.content } 
              : file
          )
        );
        
        // 这里可以添加显示预览模态框的代码
      } else {
        throw new Error(response.msg || '预览文件失败');
      }
    } catch (error) {
      console.error('预览文件失败:', error);
      // 可以添加错误提示
    }
  };

  const handleRetry = async (messageId: string) => {
    const activeConversation = state.conversations.find(
      conv => conv.id === state.activeConversationId
    );
    
    if (!activeConversation) return;
    
    // 找到失败的消息
    const failedMessage = activeConversation.messages.find(
      msg => msg.id === messageId && msg.status === 'failed'
    );
    
    if (!failedMessage) return;
    
    // 更新消息状态为发送中
      setState(prev => ({
        ...prev,
        conversations: prev.conversations.map(conv => {
          if (conv.id === prev.activeConversationId) {
            return {
              ...conv,
              messages: conv.messages.map(msg =>
              msg.id === messageId ? { ...msg, status: 'sending' } : msg
              )
            };
          }
          return conv;
      }),
      isTyping: true
    }));
    
    try {
      // 调用重试API
      const response = await chatApi.retryMessage(messageId, state.activeConversationId);
      
      if (response.code === 200) {
        // 创建AI回复消息
        const aiMessage: Message = {
          id: response.data.message.id,
          content: response.data.message.content,
          sender: 'ai',
          timestamp: new Date(response.data.message.timestamp),
          status: 'sent'
        };
        
        // 更新状态
        setState(prev => {
          const updatedConversations = prev.conversations.map(conv => {
            if (conv.id === prev.activeConversationId) {
              return {
                ...conv,
                messages: [
                  ...conv.messages.map(msg =>
                    msg.id === messageId ? { ...msg, status: 'sent' } : msg
                  ),
                  aiMessage
                ],
                timestamp: new Date()
              };
            }
            return conv;
          });

          return {
            ...prev,
            conversations: updatedConversations,
            isTyping: false
          };
        });
      } else {
        throw new Error(response.msg || '重试消息失败');
      }
    } catch (error) {
      console.error('重试消息失败:', error);
      
      // 更新消息状态为失败
      setState(prev => ({
        ...prev,
        conversations: prev.conversations.map(conv => {
          if (conv.id === prev.activeConversationId) {
            return {
              ...conv,
              messages: conv.messages.map(msg =>
                msg.id === messageId ? { ...msg, status: 'failed' } : msg
              )
            };
          }
          return conv;
        }),
        isTyping: false
      }));
    }
  };

  const handleNewChat = () => {
    setState(prev => ({
      ...prev,
      activeConversationId: null
    }));
  };

  // 处理删除会话
  const handleDeleteConversation = async (id: string) => {
    try {
      // 调用删除会话API
      const response = await chatApi.deleteConversation(id);
      
      if (response.code === 1) {
        console.log('会话删除成功:', id);
        
        // 更新状态
        setState(prev => {
          const updatedConversations = prev.conversations.filter(conv => conv.id !== id);
          
          // 如果删除的是当前活跃会话，则设置新的活跃会话
          let newActiveId = prev.activeConversationId;
          if (id === prev.activeConversationId) {
            newActiveId = updatedConversations.length > 0 ? updatedConversations[0].id : null;
          }
          
          return {
            ...prev,
            conversations: updatedConversations,
            activeConversationId: newActiveId
          };
        });
      } else {
        console.warn('删除会话失败:', response.msg);
        throw new Error(response.msg || '删除会话失败');
      }
    } catch (error) {
      console.error('删除会话失败:', error);
      
      // 如果API调用失败，仍然从本地状态中删除会话
      setState(prev => {
        const updatedConversations = prev.conversations.filter(conv => conv.id !== id);
        
        // 如果删除的是当前活跃会话，则设置新的活跃会话
        let newActiveId = prev.activeConversationId;
        if (id === prev.activeConversationId) {
          newActiveId = updatedConversations.length > 0 ? updatedConversations[0].id : null;
        }
        
        return {
          ...prev,
          conversations: updatedConversations,
          activeConversationId: newActiveId
        };
      });
    }
  };

  const activeConversation = state.conversations.find(
    conv => conv.id === state.activeConversationId
  );

  // 处理知识库问答
  const handleKnowledgeQuestion = async (question: string) => {
    try {
      console.log('开始知识库问答:', question);
      
      // 创建一个临时会话 ID，如果需要的话
      const tempSessionId = state.activeConversationId || null;
      
      // 调用知识库问答 API
      const response = await knowledgeApi.askQuestion(question, tempSessionId);
      
      if (response.code === 1 || response.code === 200) {
        console.log('知识库问答成功:', response.data);
        
        // 创建 AI 回复消息
        const aiMessage: Message = {
          id: response.data.id ? String(response.data.id) : `ai-${Date.now()}`,
          content: response.data.content || '抱歉，我无法回答这个问题。',
          sender: 'ai',
          timestamp: response.data.createdAt ? new Date(response.data.createdAt) : new Date(),
          status: 'sent',
          source: {
            fileName: '知识库',
            fileId: 'knowledge-base'
          }
        };
        
        // 返回 AI 回复消息，让 KnowledgeBase 组件更新消息列表
        return aiMessage;
      } else {
        console.warn('知识库问答失败:', response.msg);
        
        // 创建错误消息
        const errorMessage: Message = {
          id: `error-${Date.now()}`,
          content: '抱歉，我无法回答这个问题。',
          sender: 'ai',
          timestamp: new Date(),
          status: 'failed',
          errorMessage: response.msg || '知识库问答失败'
        };
        
        // 返回错误消息，让 KnowledgeBase 组件更新消息列表
        return errorMessage;
      }
    } catch (error) {
      console.error('知识库问答失败:', error);
      
      // 创建错误消息
      const errorMessage: Message = {
        id: `error-${Date.now()}`,
        content: '抱歉，我无法回答这个问题。',
        sender: 'ai',
        timestamp: new Date(),
        status: 'failed',
        errorMessage: error instanceof Error ? error.message : '知识库问答失败'
      };
      
      // 返回错误消息，让 KnowledgeBase 组件更新消息列表
      return errorMessage;
    }
  };

  // 处理单个文件嵌入
  const handleEmbedFile = async (fileId: string) => {
    try {
      console.log('开始嵌入文件:', fileId);
      
      // 更新文件状态为处理中
      setKnowledgeFiles(prev => 
        prev.map(file => 
          file.id === fileId 
            ? { ...file, embeddingStatus: 'processing' } 
            : file
        )
      );
      
      const response = await knowledgeApi.embedFile(fileId);
      
      if (response.code === 1 || response.code === 200) {
        console.log('文件嵌入成功:', response.data);
        
        // 更新文件状态为已完成
        setKnowledgeFiles(prev => 
          prev.map(file => 
            file.id === fileId 
              ? { 
                  ...file, 
                  embeddingStatus: 'completed',
                  lastEmbeddedAt: new Date()
                } 
              : file
          )
        );
        
        // 刷新知识库文档列表
        loadKnowledgeFiles();
        
        return response.data;
      } else {
        console.warn('文件嵌入失败:', response.msg);
        
        // 更新文件状态为失败
        setKnowledgeFiles(prev => 
          prev.map(file => 
            file.id === fileId 
              ? { ...file, embeddingStatus: 'failed' } 
              : file
          )
        );
        
        throw new Error(response.msg || '文件嵌入失败');
      }
    } catch (error) {
      console.error('文件嵌入失败:', error);
      throw error;
    }
  };

  // 处理所有文件嵌入
  const handleEmbedAllFiles = async () => {
    try {
      console.log('开始一键嵌入所有文件');
      
      // 更新所有文件状态为处理中
      setKnowledgeFiles(prev => 
        prev.map(file => ({ ...file, embeddingStatus: 'processing' }))
      );
      
      const response = await knowledgeApi.embedAllFiles();
      
      if (response.code === 1 || response.code === 200) {
        console.log('所有文件嵌入成功:', response.data);
        
        // 更新所有文件状态为已完成
        setKnowledgeFiles(prev => 
          prev.map(file => ({ 
            ...file, 
            embeddingStatus: 'completed',
            lastEmbeddedAt: new Date()
          }))
        );
        
        // 刷新知识库文档列表
        loadKnowledgeFiles();
        
        return response.data;
      } else {
        console.warn('所有文件嵌入失败:', response.msg);
        
        // 更新所有文件状态为失败
        setKnowledgeFiles(prev => 
          prev.map(file => ({ ...file, embeddingStatus: 'failed' }))
        );
        
        throw new Error(response.msg || '所有文件嵌入失败');
      }
    } catch (error) {
      console.error('所有文件嵌入失败:', error);
      throw error;
    }
  };

  // 处理会话选择
  const handleSelectConversation = async (id: string) => {
    console.log('选择会话:', id);
    
    // 先设置活跃会话 ID，这样用户界面会立即响应
    setState(prev => ({
      ...prev,
      activeConversationId: id
    }));
    
    try {
      // 检查该会话是否已经加载了消息
      const conversation = state.conversations.find(conv => conv.id === id);
      
      // 如果会话存在但没有消息或消息为空数组，则加载会话详情
      if (conversation && (!conversation.messages || conversation.messages.length === 0)) {
        console.log('加载会话详情:', id);
        
        // 显示加载状态
        setState(prev => ({
          ...prev,
          isTyping: true
        }));
        
        // 调用 API 获取会话详情
        const response = await chatApi.getSessionDetail(id);
        
        if (response.code === 1 && Array.isArray(response.data)) {
          console.log('成功获取会话详情:', response.data);
          
          // 转换消息格式
          const messages: Message[] = response.data.map((msg: any) => ({
            id: msg.id?.toString() || `msg-${Date.now()}-${Math.random()}`,
            content: msg.content || '',
            sender: msg.type === 'USER' ? 'user' : 'ai',
            timestamp: new Date(msg.createdAt || Date.now()),
            status: 'sent'
          }));
          
          // 更新会话的消息
          setState(prev => ({
            ...prev,
            conversations: prev.conversations.map(conv => 
              conv.id === id ? { ...conv, messages } : conv
            ),
            isTyping: false
          }));
        } else {
          console.warn('获取会话详情失败或格式不正确:', response);
          // 设置为空消息数组，避免反复请求
          setState(prev => ({
            ...prev,
            conversations: prev.conversations.map(conv => 
              conv.id === id ? { ...conv, messages: [] } : conv
            ),
            isTyping: false
          }));
        }
      } else {
        console.log('会话已加载或不存在:', id);
      }
    } catch (error) {
      console.error('加载会话详情失败:', error);
      setState(prev => ({ ...prev, isTyping: false }));
    }
  };

  // 加载知识库会话历史
  const loadKnowledgeChatHistory = async (sessionId?: string) => {
    try {
      console.log('开始加载知识库会话历史...');
      const response = await knowledgeApi.getChatHistory(sessionId);
      
      if (response.code === 1) {
        console.log('成功获取知识库会话历史:', response.data);
        
        // 检查响应数据是否为数组
        if (!Array.isArray(response.data)) {
          console.warn('知识库会话历史数据不是数组:', response.data);
          return [];
        }
        
        // 转换消息数据格式
        const messages = response.data.map((msg: any) => {
          // 打印每个消息对象，帮助调试
          console.log('处理消息对象:', msg);
          
          // 确保消息对象和必要的属性存在
          if (!msg) {
            console.warn('消息对象为空');
            return null;
          }
          
          // 根据 messageDetailVO 的结构映射属性
          return {
            id: msg.id ? String(msg.id) : `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
            content: msg.content || '',
            sender: msg.type === 'USER' ? 'user' : 'ai',
            timestamp: msg.createdAt ? new Date(msg.createdAt) : new Date(),
            status: 'sent',
            source: msg.type === 'AI' ? {
              fileName: '知识库',
              fileId: 'knowledge-base'
            } : undefined
          };
        }).filter(Boolean); // 过滤掉 null 值
        
        console.log('转换后的消息列表:', messages);
        return messages;
      } else {
        console.warn('获取知识库会话历史失败:', response.msg);
        return [];
      }
    } catch (error) {
      console.error('加载知识库会话历史失败:', error);
      console.error('错误详情:', error instanceof Error ? error.message : String(error));
      return [];
    }
  };

  // 处理联网对话
  const handleWebSearchChat = async (content: string) => {
    if (!content.trim()) return;

    console.log('准备发送联网对话消息:', content);
    
    // 创建用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      content,
      sender: 'user',
      timestamp: new Date(),
      status: 'sending'
    };
    
    // 添加用户消息到当前会话
    setState(prev => {
      // 如果没有活跃会话，创建一个新会话
      if (!prev.activeConversationId) {
        const newConversation: Conversation = {
          id: `temp-${Date.now()}`,
          title: content.slice(0, 30) || '新联网对话',
          lastMessage: content,
          timestamp: new Date(),
          messages: [userMessage]
        };
        
        return {
          ...prev,
          // 将新会话放在数组的最前面
          conversations: [newConversation, ...prev.conversations],
          activeConversationId: newConversation.id,
          isTyping: true
        };
      }
      
      // 如果有活跃会话，添加消息到该会话
      const updatedConversations = prev.conversations.map(conv => {
        if (conv.id === prev.activeConversationId) {
          return {
            ...conv,
            messages: [...conv.messages, userMessage],
            lastMessage: content,
            timestamp: new Date()
          };
        }
        return conv;
      });
      
      return {
        ...prev,
        conversations: updatedConversations,
        isTyping: true
      };
    });

    try {
      // 获取用户ID和token
      const userId = localStorage.getItem('userId');
      const token = localStorage.getItem('webToken');
      
      console.log('用户ID:', userId);
      console.log('Token 存在:', !!token);
      
      if (!userId || !token) {
        // 显示错误消息，但不跳转
        console.error('用户未登录或会话已过期');
        
        // 更新消息状态为失败
    setState(prev => ({
      ...prev,
          conversations: prev.conversations.map(conv => {
            if (conv.id === prev.activeConversationId) {
              return {
                ...conv,
                messages: conv.messages.map(msg =>
                  msg.id === userMessage.id ? { 
                    ...msg, 
                    status: 'failed',
                    errorMessage: '用户未登录或会话已过期，请重新登录'
                  } : msg
                )
              };
            }
            return conv;
          }),
          isTyping: false
        }));
        
        return;
      }
      
      // 发送联网对话消息到服务器
      console.log('调用联网对话 API');
      const response = await searchApi.webSearchChat(
        content, 
        state.activeConversationId || undefined
      );
      
      console.log('收到联网对话响应:', response);
      
      // 检查响应是否成功
      if (response.code === 1) {
        console.log('联网对话成功，创建 AI 回复');
        
        // 创建AI回复消息
        const aiMessage: Message = {
          id: `ai-${Date.now()}`,
          content: response.data.content || '抱歉，我无法理解您的问题。',
          sender: 'ai',
          timestamp: new Date(response.data.createdAt) || new Date(),
          status: 'sent',
          source: {
            fileName: '联网搜索',
            fileId: 'web-search'
          }
        };
        
        // 如果返回了会话ID，更新当前会话ID
        if (response.data.sessionId) {
          const sessionId = String(response.data.sessionId);
          
          setState(prev => {
            // 如果当前会话是临时会话，需要更新会话ID
            if (prev.activeConversationId?.startsWith('temp-')) {
              const updatedConversations = prev.conversations.map(conv => {
                if (conv.id === prev.activeConversationId) {
                  return {
                    ...conv,
                    id: sessionId,
                    messages: [
                      ...conv.messages.map(msg => 
                        msg.id === userMessage.id ? { ...msg, status: 'sent' } : msg
                      ),
                      aiMessage
                    ],
                    timestamp: new Date()
                  };
                }
                return conv;
              });
              
              return {
                ...prev,
                conversations: updatedConversations,
                activeConversationId: sessionId,
                isTyping: false
              };
            }
            
            // 如果不是临时会话，只更新消息
            const updatedConversations = prev.conversations.map(conv => {
              if (conv.id === prev.activeConversationId) {
                return {
                  ...conv,
                  messages: [
                    ...conv.messages.map(msg => 
                      msg.id === userMessage.id ? { ...msg, status: 'sent' } : msg
                    ),
                    aiMessage
                  ],
                  timestamp: new Date()
                };
              }
              return conv;
            });
            
            return {
              ...prev,
              conversations: updatedConversations,
              isTyping: false
            };
          });
        } else {
          // 如果没有返回会话ID，只更新消息
          setState(prev => {
            const updatedConversations = prev.conversations.map(conv => {
              if (conv.id === prev.activeConversationId) {
                return {
                  ...conv,
                  messages: [
                    ...conv.messages.map(msg => 
                      msg.id === userMessage.id ? { ...msg, status: 'sent' } : msg
                    ),
                    aiMessage
                  ],
                  timestamp: new Date()
                };
              }
              return conv;
            });
            
            return {
              ...prev,
              conversations: updatedConversations,
              isTyping: false
            };
          });
        }
        
        // 延迟刷新会话列表，避免屏幕闪烁
        setTimeout(() => {
          refreshSessionList(false); // 传入 false 表示静默刷新，不更新 UI
        }, 1000);
      } else {
        console.warn('响应码不是 1:', response.code);
        throw new Error(response.msg || '联网对话失败');
      }
    } catch (error) {
      console.error('联网对话失败:', error);
      
      // 获取错误消息
      const errorMessage = error instanceof Error 
        ? error.message 
        : '联网对话失败，请稍后再试';
      
      // 更新消息状态为失败
    setState(prev => ({
      ...prev,
        conversations: prev.conversations.map(conv => {
          if (conv.id === prev.activeConversationId) {
            return {
              ...conv,
              messages: conv.messages.map(msg =>
                msg.id === userMessage.id ? { 
                  ...msg, 
                  status: 'failed',
                  errorMessage
                } : msg
              )
            };
          }
          return conv;
        }),
        isTyping: false
      }));
    }
  };

  return (
    <Routes>
      <Route path="/" element={
        <div className="flex min-h-screen bg-gray-50">
          {!isAuthenticated ? (
            <Login onLogin={handleLogin} onRegisterClick={() => navigate('/register')} />
          ) : (
            <>
              {/* 侧边栏切换按钮 - 仅在侧边栏折叠时显示 */}
              {sidebarCollapsed && (
                <button
                  onClick={() => setSidebarCollapsed(false)}
                  className="fixed left-0 top-1/2 transform -translate-y-1/2 bg-white p-2 rounded-r-lg shadow-md z-10 hover:bg-gray-100"
                >
                  <ChevronRight className="w-5 h-5 text-gray-600" />
                </button>
              )}

              {/* 会话列表侧边栏 */}
              <div className={`${sidebarCollapsed ? 'hidden' : 'block'} relative`}>
                <ConversationList
                  conversations={state.conversations}
                  activeId={state.activeConversationId}
                  searchQuery={state.searchQuery}
                  onSearch={(query) => setState(prev => ({ ...prev, searchQuery: query }))}
                  onSelect={handleSelectConversation}
                  onDelete={handleDeleteConversation}
                  onNewChat={handleNewChat}
                />

                {/* 折叠侧边栏按钮 */}
                <button
                  onClick={() => setSidebarCollapsed(true)}
                  className="absolute right-0 top-1/2 transform -translate-y-1/2 translate-x-1/2 bg-white p-2 rounded-full shadow-md z-10 hover:bg-gray-100"
                >
                  <ChevronLeft className="w-5 h-5 text-gray-600" />
                </button>
              </div>

              {/* 聊天区域 */}
              <div className="flex-1 flex flex-col h-screen">
                {/* 头部 */}
                <div className="bg-white border-b px-6 py-4 flex items-center justify-between">
                  <div className="flex items-center">
                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                      <Bot className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <h1 className="text-xl font-semibold text-gray-800">AI 助手</h1>
                      <p className="text-sm text-gray-500">随时为您提供帮助</p>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    {/* 注销按钮 */}
                    <button
                      onClick={handleLogout}
                      className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors"
                    >
                      注销
                    </button>
                    
                    {/* 知识库按钮 */}
                    <button
                      onClick={() => setShowKnowledgeBase(true)}
                      className="flex items-center gap-2 px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors"
                    >
                      <Book className="w-5 h-5" />
                      <span>知识库</span>
                    </button>
                  </div>
                </div>

                {/* 聊天内容 */}
                <div
                  ref={chatContainerRef}
                  className="flex-1 overflow-y-auto p-6"
                >
                  {activeConversation ? (
                    // 显示活跃会话的消息
                    <>
                      {activeConversation.messages.map((message) => (
                        <ChatMessage
                          key={message.id}
                          message={message}
                          onRetry={
                            message.status === 'failed' ? handleRetry : undefined
                          }
                        />
                      ))}
                    </>
                  ) : (
                    // 欢迎界面 - 当没有活跃会话时显示
                    <div className="flex-1 flex flex-col items-center justify-center px-6">
                      <div className="w-20 h-20 rounded-full bg-blue-100 flex items-center justify-center mb-6">
                        <Bot className="w-12 h-12 text-blue-600" />
                      </div>
                      <h2 className="text-2xl font-semibold text-gray-800 mb-2">欢迎使用 AI 助手</h2>
                      <p className="text-gray-500 mb-8 text-center max-w-md">
                        开始一个新的对话，或者从左侧选择一个已有的对话。您可以询问任何问题，我会尽力帮助您。
                      </p>
                      <div className="w-full max-w-2xl">
                        <ChatInput
                          onSendMessage={handleSendMessage}
                          onWebSearchChat={handleWebSearchChat}
                          disabled={state.isTyping}
                          placeholder="有什么可以帮助您的？"
                        />
                      </div>
                    </div>
                  )}
                </div>

                {/* 输入区域 - 仅在有活动对话时显示 */}
                {activeConversation && (
                  <ChatInput
                    onSendMessage={handleSendMessage}
                    onWebSearchChat={handleWebSearchChat}
                    disabled={state.isTyping}
                  />
                )}
              </div>

              {/* 知识库模态框 */}
              {showKnowledgeBase && (
                <KnowledgeBase
                  onClose={() => setShowKnowledgeBase(false)}
                  files={knowledgeFiles}
                  onFileUpload={handleFileUpload}
                  onFileDelete={handleFileDelete}
                  onFilePreview={handleFilePreview}
                  onAskQuestion={handleKnowledgeQuestion}
                  onEmbedFile={handleEmbedFile}
                  onEmbedAllFiles={handleEmbedAllFiles}
                  onLoadChatHistory={loadKnowledgeChatHistory}
                />
              )}
            </>
          )}
        </div>
      } />
      <Route path="/login" element={<Login onLogin={handleLogin} onRegisterClick={() => navigate('/register')} />} />
      <Route path="/register" element={<Register />} />
      {/* 将其他路由重定向到首页 */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

export default App;